package ar.edu.unlu.sistemas.p2p.business.msg;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;

import ar.edu.unlu.sistemas.p2p.business.task.Result;

public class QueryResponseMessage extends Message {
	
	private Collection<QueryResult> results;
	public static final String TAG_RESULTS = "results";
	
	public Collection<QueryResult> getResults() {
		return results;
	}

	public void setResults(Collection<QueryResult> results) {
		this.results = results;
	}
	
	public QueryResponseMessage(Document xmlDoc) {
		super(xmlDoc);
		// TODO Auto-generated constructor stub
	}

	public QueryResponseMessage(int type) {
		super(type);
		// TODO Auto-generated constructor stub
	}

	public QueryResponseMessage(String msgId, int type) {
		super(msgId, type);
		// TODO Auto-generated constructor stub
	}
	
	public QueryResponseMessage() {
		super(MessageFactory.CODE_QUERY_RESP);
	}
	
	public void addResult(QueryResult result) {
		if (this.getResults() == null) {
			this.setResults(new ArrayList<QueryResult>());
		}
		this.getResults().add(result);
	}
	
	public Collection<Result> getAllResults() {
		Collection<Result> out = new ArrayList<Result>();
		if (this.getResults() != null) {
			Iterator<QueryResult> resultsIt = this.getResults().iterator();
			while (resultsIt.hasNext()) {
				out.add(resultsIt.next().getVO());
			}
		}
		return out;
	}
	
	public Element toXMLElement() {
		Element root = super.toXMLElement();
		Element elResults = new Element(TAG_RESULTS);
		if (this.getResults() != null) {
			Iterator<QueryResult> resultsIt = this.getResults().iterator();
			while (resultsIt.hasNext()) {
				elResults.addContent(resultsIt.next().toXMLElement());
			}
		} else {
			elResults.setText(null);
		}
		root.addContent(elResults);
		return root;
	}
	
	protected Element buildFromXMLDoc(Document xmlDoc) {
		Element root = super.buildFromXMLDoc(xmlDoc);
		this.setResults(new ArrayList<QueryResult>());
		Element elResults = root.getChild(TAG_RESULTS);
		if (elResults.getChildren(PingResult.TAG_ROOT) != null) {
			Iterator<Element> elResultsIt = elResults.getChildren(QueryResult.TAG_ROOT).iterator();
			while (elResultsIt.hasNext()) {	
				this.getResults().add(QueryResult.buildFromXMLElement(elResultsIt.next()));
			}
		}
		return root;
	}
	

}
